package com.changgou.order.Timing;

import com.alibaba.fastjson.JSONObject;
import com.changgou.order.pojo.Order;
import com.changgou.order.service.OrderService;
import com.changgou.pay.feign.PayFeign;
import com.changgou.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @ClassName: OrderTiming
 * @Author: ZWJ
 * @Date: 2020-09-09 20:06
 * @Synopsis: Null
 **/
@Component
public class OrderTiming {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PayFeign payFeign;
    @Autowired
    private OrderService orderService;
    //定时清理订单
   @Scheduled(fixedRate = 500)
    public void deleteOrder(){
        //查询redis中订单数据
        List<Object> orderss = redisTemplate.boundHashOps("Order").values();
        if (orderss!=null){
            for (Object orders : orderss) {
                String stringOrder = orders.toString();
                Order order = JSONObject.parseObject(stringOrder, Order.class);
                //查询订单的支付状态
                Result<Map<String, String>> mapResult = payFeign.queryStatus(order.getId());
                //取出订单的支付状态数据
                Map<String, String> data = mapResult.getData();
                //返回状态码
                String return_code = data.get("return_code");
                //业务结果
                String result_code = data.get("result_code");
                //支付状态
                String trade_state = data.get("trade_state");

                    if ("SUCCESS".equals(result_code)
                            &&"SUCCESS".equals(return_code)&&"SUCCESS".equals(trade_state)){
                        //支付成功
                        orderService.updateStatus(order.getId(),data.get("transaction_id").toString());
                    }
                    if ("SUCCESS".equals(result_code)
                            &&"SUCCESS".equals(return_code)&&"NOTPAY".equals(trade_state)){
                        //未支付，不做处理
                    }
                    if ("SUCCESS".equals(result_code)
                            &&"SUCCESS".equals(return_code)&&"PAYERROR".equals(trade_state)){
                        //支付失败，对订单进行删除
                        orderService.deleteOrder(order.getId());
                    }
                }
        }
    }

    public static void main(String[] args) {
        Set list=new HashSet();

    }
}
